package opencv;

import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.videoio.VideoCapture;
import ui.MainUI;

public class FaceCv {
    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    private MainUI mainUI;
    private static int index = 0;
    private static boolean flag = false;

    //识别人脸
    public void videoFace() {
        VideoCapture capture = new VideoCapture(0);
        Mat image = new Mat();
        //int index = 0;
        if (capture.isOpened()) {
            while (true) {
                capture.read(image);
//                getFace(image);
//
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }

                HighGui.imshow("实时人脸识别", getFace(image));
                index = HighGui.waitKey(1);
                if (index == 27) {
                    break;
                }
            }
        }
    }

    //绘制矩形
    public Mat getFace(Mat image) {
        //读取OpenCV自带的人脸识别特征XML文件
        CascadeClassifier facebook = new CascadeClassifier("C:\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml");
        //特征匹配类
        MatOfRect face = new MatOfRect();
        //特征匹配
        facebook.detectMultiScale(image, face);
        Rect[] rects = face.toArray();

        if (rects.length != 0) {
//            if (index == 0) {
//                if (!flag) {
//                    mainUI = new MainUI();
//                    flag = true;
//                }
//                mainUI.setVisible(true);
//                mainUI.setAlwaysOnTop(true);
//                index = 1;
//            }
        } else {
//            if (index == 1) {
//                mainUI.setVisible(false);
//                index = 0;
//            }
        }

        //为每张识别到的人脸画一个圈
        for (int i = 0; i < rects.length; i++) {
            Imgproc.rectangle(image, new Point(rects[i].x, rects[i].y), new Point(rects[i].x + rects[i].width, rects[i].y + rects[i].height), new Scalar(0, 255, 0));
            Imgproc.putText(image, "Human", new Point(rects[i].x, rects[i].y), Imgproc.FONT_HERSHEY_SCRIPT_SIMPLEX, 1.0, new Scalar(0, 255, 0), 1, Imgproc.LINE_AA, false);
        }
        return image;
    }
}
